#pragma once
#include <iostream>
#include <memory>
#include "Socket.hpp"
#include "Connection.hpp"
#include "InetAddr.hpp"
#include "IOService.hpp"
#include "Reactor.hpp"
#include "Calculator.hpp"
class Listener: public Connection
{
public:
    Listener(int port):_port(port),_listen_socket(std::make_unique<TcpSocket>(port))
    {
        _listen_socket->BuildTcpSocket();
        SetSockfd(_listen_socket->Fd());
        SetEvents(EPOLLIN|EPOLLET);
    }

    virtual void Recv() override
    {
        while(1)
        {
            InetAddr peer;
            int aerrno;
            int newsockfd = _listen_socket->Accept(&peer,&aerrno);
            LOG(LogLevel::INFO)<<"accept 获得新链接sockfd:"<<newsockfd<<"errno: "<<aerrno;
            //LOG(LogLevel::DEBUG)<<"获得新连接sockfd: "<<sockfd;
            if(newsockfd>0)
            {
                auto conn = std::make_shared<IOService>(newsockfd);
                conn->SetEvents(EPOLLIN);
                conn->RegisterOnMessage(HandlerRequest);
                GetOwner()->InsertConnection(conn);
            }
            else 
            {
                if(aerrno==EAGAIN)
                {
                    LOG(LogLevel::DEBUG)<<"accept处理完所有连接";
                    break;
                }
                else if(aerrno==EINTR)
                {
                    LOG(LogLevel::DEBUG)<<"accept被信号中断，continue";
                    continue;
                }
                else
                {
                    LOG(LogLevel::ERROR)<<"accept error";
                    break;
                }
            }

        }

    }
    virtual void Send() override
    {

    }
    virtual void Except() override
    {

    }
    int ListenSockfd()
    {
        return _listen_socket->Fd();
    }

private:  
    int _port;
    std::unique_ptr<Socket> _listen_socket;
};